<template>
  <div class="product-stat full-height page-content content bg-white"  ref="contentBox">
    <collapse ref="collapse">
      <template v-slot:content>
        <yz-condition-filter
          v-model="queryParams"
          @resetSearch="resetSearch"
          @onSubmit="onSearch"
          style="margin-top: 4px;"
        >
          <fuzzy-search
            class="margin-r-20"
            v-model.trim="queryParams.orderNum"
            title="订单号"
            :isShowValue="false"
            :fuzzyFunc="fuzzyFunc"
          />
          <fuzzy-search
            class="margin-r-20"
            v-model.trim="queryParams.productId"
            title="产品"
            fuzzyValue="number"
            :fuzzyFunc="fuzzyFunPru"
          />
          <yz-input
            v-model.trim="queryParams.productSpec"
            class="q-mr-md"
            title="产品规格"
          />
          <yz-input
            v-model="queryParams.startRange"
            inputType="date"
            isTip
            class="margin-b-20 margin-r-20"
            title="计划开工"
          ></yz-input>
          <yz-input
            v-model="queryParams.endRange"
            inputType="date"
            class="margin-b-20 margin-r-20"
            isTip
            title="计划完工"
          ></yz-input>
          <yz-input
            v-model="queryParams.actualStartRange"
            inputType="date"
            isTip
            class="margin-b-20 margin-r-20"
            title="实际开工"
          ></yz-input>
          <yz-input
            v-model="queryParams.actualEndRange"
            inputType="date"
            isTip
            class="margin-b-20 margin-r-20"
            title="实际完工"
          ></yz-input>
        </yz-condition-filter>
        <div class="form-inline bottom"
             style="justify-content: space-between; padding-bottom: 14px">
          <div class="left box">
            <q-btn class="btn margin-r-10"
                   outline
                   color="primary"
                   label="导出Excel"
                   :disable="!tableData.length"
                   @click="exportExcel"/>
          </div>
        </div>
      </template>
    </collapse>
    <!--  table表格-->
    <q-table :data="tableData"
             :columns="tableColumns"
             row-key="indexId"
             class="scroll  myTable"
             separator="cell"
             :pagination.sync="pagination"
             :hide-bottom="tableData.length > 0"
             :loading="isTableLoading"
             style="margin-top: 6px"
             color="primary">
      <template v-slot:header-cell="props">
        <q-th :props="props" class="t-head-cell">
          {{ props.col.label }}
        </q-th>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td>{{props.row.serialNumber}}</q-td>
          <q-td>{{props.row.orderNumber}}</q-td>
          <template v-for="(key, keyIndex) in ['orderBatch', 'workshopPlanningNumber', 'productNumber', 'productName', 'productStandard', 'planningStartTime', 'planningEndTime']">
            <q-td :key="key + '_' + keyIndex" class="no-padding full-height">
              <div class="full-height">

                  <div class="item flex items-center td-item rowData" v-for="(item, index) in props.row.workshopPlannings" :key="index" :style="{height: `${item.processPlannings ? item.processPlannings.length * tdHeight : 0}px`}">
                    <td-spec :rowData="item" class="item td-item" style="padding: 0; height: auto" v-if="key === 'productStandard'" />
                    <template v-else>
                      {{item[key] || '--'}}
                    </template>
                  </div>
              </div>
            </q-td>
          </template>
          <template v-for="(key, keyIndex) in sortDetailColums">
            <q-td :key="key + '_' + keyIndex" class="no-padding" v-show="visibleColumns.includes(key)">
              <div class="flex column" :style="{height: props.row[key] ? props.row[key].length * tdHeight : 0 + 'px'}">
                <div class="item flex items-center td-item td-item-min" v-for="(item, index) in props.row[key]" :key="index">
                  {{item}}
                </div>
              </div>
            </q-td>
          </template>
        </q-tr>
      </template>
    </q-table>
    <yz-pagination v-model="pagination" @onSearch="getList"/>
  </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import moment from 'moment'
import productStat from '../../boot/statistics/product-stat'
import _ from 'lodash'
import { addListener } from 'resize-detector'
import { mapGetters } from 'vuex'
import { getOrderNumList } from '../../boot/plan/plan-progress'
function getProductListNew (val) {
  return productStat.getSearchMaterials(val).then(res => {
    return Promise.resolve(res)
  })
}
function getOrderNumListNew (val) {
  const params = {
    pageNum: 1,
    pageSize: 100000,
    typeValue: val
  }
  return getOrderNumList(params).then(res => {
    if (res.success) {
      let listData = []
      res.data.list.forEach((item, index) => {
        listData.push({
          label: item,
          value: `${item}#@$` // 避免label与value重复，value拼接固定字符
        })
      })
      res.data = listData
    }
    return Promise.resolve(res)
  })
}
export default {
  name: 'product-stat',
  components: {
    Collapse
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  data () {
    return {
      fuzzyFunc: getOrderNumListNew,
      fuzzyFunPru: getProductListNew,
      queryParams: {
        orderNum: '',
        productId: null,
        startRange: [null, null],
        endRange: [null, null],
        actualStartRange: [null, null],
        actualEndRange: [null, null],
        productSpec: ''
      },
      isTableLoading: false,
      requestId: null, // 导出唯一标识
      index: 0, // 序号
      orderOptions: [], // 订单号数据源
      materialNameOptions: [], // 产品名称数据源
      tableColumns: [
        { name: 'serialNumber', label: '序号', field: 'serialNumber', align: 'left' },
        { name: 'orderNumber', label: '订单号', field: 'orderNumber', align: 'left' },
        { name: 'orderBatch', label: '批次号', field: 'orderBatch', align: 'left' },
        { name: 'workshopPlanningNumber', label: '计划编号', field: 'workshopPlanningNumber', align: 'left' },
        { name: 'productNumber', label: '产品编号', field: 'productNumber', align: 'left' },
        { name: 'productName', label: '产品名称', field: 'productName', align: 'left' },
        { name: 'productStandard', label: '产品规格 ', field: 'productStandard', align: 'left' },
        { name: 'planningStartTime', label: '计划开工日期', field: 'planningStartTime', align: 'left' },
        { name: 'planningEndTime', label: '计划完工日期 ', field: 'planningEndTime', align: 'left' },
        { name: 'processName', label: '工序', field: 'processName', align: 'left' },
        { name: 'actualStartTime', label: '实际开工', field: 'actualStartTime', align: 'left' },
        { name: 'actualEndTime', label: '实际完工', field: 'actualEndTime', align: 'left' },
        { name: 'planningCount', label: '计划数量', field: 'planningCount', align: 'left' },
        { name: 'actualCount', label: '实际数量', field: 'actualCount', align: 'left' },
        { name: 'achievementRate', label: '达成率', field: 'achievementRate', align: 'left' },
        { name: 'defectiveCount', label: '不良数', field: 'defectiveCount', align: 'left' },
        { name: 'qualifiedCount', label: '合格数 ', field: 'qualifiedCount', align: 'left' },
        { name: 'passRate', label: '合格率', field: 'passRate', align: 'left' },
        { name: 'defectiveRate', label: '不良率', field: 'defectiveRate', align: 'left' },
        { name: 'qualityCount', label: '质检数量', field: 'qualityCount', align: 'left' },
        { name: 'qualityDefectiveRate', label: '质检不良率', field: 'qualityDefectiveRate', align: 'left' }
      ],
      sortDetailColums: [],
      // 表格内容
      tableData: [],
      columnsName: {}, // 列名
      exportParams: {}, // 打印参数
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      tdHeight: 48 // 单元格高度
    }
  },
  created () {
    this.init()
    this.$nextTick(() => {
      this.tdHeight = document.getElementsByClassName('t-head-cell')[0].clientHeight + 1
    })
  },
  mounted () {
    addListener(this.$refs.contentBox, this.$utils.debounce(() => {
      this.tdHeight = document.getElementsByClassName('t-head-cell')[0].clientHeight + 1
    }, 50))
  },
  methods: {
    init () {
      this.getList()
      let visibleColumns = []
      let columnsName = {}
      this.tableColumns.forEach(item => {
        visibleColumns.push(item.name)
        columnsName[item.name] = item.label
      })
      this.columnsName = columnsName
      this.visibleColumns = visibleColumns
      this.sortDetailColums = _.cloneDeep(visibleColumns).slice(9, visibleColumns.length)
    },
    getList () {
      let params = {}
      this.isTableLoading = true
      !_.isEmpty(this.queryParams.orderNum) && (params['orderNumber'] = this.queryParams.orderNum)
      !_.isEmpty(this.queryParams.productId) && (params['productId'] = this.queryParams.productId)
      !_.isNil(this.queryParams.startRange[0]) && (params['planningStartAfter'] = moment(this.queryParams.startRange[0]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.startRange[1]) && (params['planningStartBefore'] = moment(this.queryParams.startRange[1]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.endRange[0]) && (params['planningEndAfter'] = moment(this.queryParams.endRange[0]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.endRange[1]) && (params['planningEndBefore'] = moment(this.queryParams.endRange[1]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.actualStartRange[0]) && (params['actualStartAfter'] = moment(this.queryParams.actualStartRange[0]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.actualStartRange[1]) && (params['actualStartBefore'] = moment(this.queryParams.actualStartRange[1]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.actualEndRange[0]) && (params['actualEndAfter'] = moment(this.queryParams.actualEndRange[0]).format('YYYY-MM-DD'))
      !_.isNil(this.queryParams.actualEndRange[1]) && (params['actualEndBefore'] = moment(this.queryParams.actualEndRange[1]).format('YYYY-MM-DD'))
      params['orderNumber'] = this.queryParams.orderNum ? _.trimEnd(this.queryParams.orderNum, '#@$') : undefined // 去固定字符
      this.exportParams = _.cloneDeep(params)
      params['pageNum'] = this.pagination.pageNum
      params['pageSize'] = this.pagination.pageSize
      this.queryParams.productSpec + '' !== '' && (params['productSpec'] = this.queryParams.productSpec)
      productStat.getProduceReports(params).then(res => {
        this.pagination.rowsNumber = res.data.total
        res.data.list.forEach((item, index) => {
          item['serialNumber'] = (this.pagination.pageNum - 1) * this.pagination.pageSize + index + 1
          this.sortDetailColums.forEach(key => {
            item[key] = []
          })
          // item.products.forEach(batch => {
          //   batch.processPlannings.forEach(sort => {
          item.workshopPlannings.forEach(batch => {
            console.log(batch, 'batch')
            batch.planningStartTime = batch.processPlannings[0].planningStartTime
            batch.planningEndTime = batch.processPlannings[batch.processPlannings.length - 1].planningEndTime
            batch.processPlannings.forEach((sort, index) => {
              item.processName.push(sort.processName)
              // item.planningStartTime.push(sort.planningStartTime)
              // item.planningEndTime.push(sort.planningEndTime)
              item.actualStartTime.push(sort.actualStartTime)
              item.actualEndTime.push(sort.actualEndTime)
              // const planningCount = _.isNil(sort.planningCount) ? 0 : Number(sort.planningCount)
              // const defectiveCount = _.isNil(sort.defectiveCount) ? 0 : Number(sort.defectiveCount)
              // const actualCount = _.isNil(sort.actualCount) ? 0 : Number(sort.actualCount)
              // const compromiseCount = _.isNil(sort.compromiseCount) ? 0 : Number(sort.compromiseCount)
              item.planningCount.push(sort.planningCount)
              item.defectiveCount.push(sort.defectiveCount)
              item.actualCount.push(sort.actualCount)
              // item.compromiseCount.push(sort.compromiseCount)
              item.qualifiedCount.push(sort.qualifiedCount)
              // // 达成率
              // item.reachRate.push(`${planningCount === 0 ? '0.00' : (actualCount / planningCount * 100).toFixed(2)}%`)
              item.achievementRate.push(sort.achievementRate)
              // // 不良率
              // item.badRate.push(`${actualCount === 0 ? '0.00' : ((defectiveCount) / actualCount * 100).toFixed(2)}%`)
              item.defectiveRate.push(sort.defectiveRate)
              item.qualityCount.push(sort.qualityCount)
              item.qualityDefectiveRate.push(sort.qualityDefectiveRate)
              // // 合格率
              // item.passRate.push(`${actualCount === 0 ? '0.00' : ((actualCount - defectiveCount) / actualCount * 100).toFixed(2)}%`)
              item.passRate.push(sort.passRate)
            })
          })
        })
        this.isTableLoading = false
        this.tableData = res.data.list
      })
      console.log(this.tableData)
      this.initTableColumns()
    },
    initTableColumns () {
      let visibleColumns = []
      let columnsName = {}
      this.tableColumns.forEach(item => {
        visibleColumns.push(item.name)
        columnsName[item.name] = item.label
      })
      this.columnsName = columnsName
      this.visibleColumns = visibleColumns
      this.sortDetailColums = _.cloneDeep(visibleColumns).slice(9, visibleColumns.length)
    },
    // 重置
    resetSearch () {
      this.queryParams.orderNum = null
      this.queryParams.productId = null
      this.queryParams.startRange = [null, null]
      this.queryParams.endRange = [null, null]
      this.queryParams.actualStartRange = [null, null]
      this.queryParams.actualEndRange = [null, null]
      this.queryParams.productSpec = ''
      this.exportParams = {}
    },
    // 提交
    onSearch () {
      this.pagination.pageNum = 1
      this.getList()
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, '生产报表.xls')
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    // 导出Excel
    exportExcel () {
      // 表格列表列，根据这个顺序排序
      const tableColums = _.cloneDeep(this.tableColumns).map(item => item.field)
      let excelHeads = []
      let exportParams = {
        ...this.exportParams,
        excelHead: []
      }
      // 重新排序要显示的列
      excelHeads = tableColums.reduce((pre, next) => {
        if (this.visibleColumns.includes(next))pre.push(next)
        return pre
      }, [])
      excelHeads.forEach(item => {
        exportParams['excelHead'].push({
          field: item,
          name: this.columnsName[item]
        })
      })
      console.log(exportParams)
      this.$q.loading.show()
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      exportParams['requestId'] = res.fileNameNew
      this.onSubscribe()
      productStat.exportProduceReports(exportParams).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    }
  }
}
</script>

<style scoped lang="stylus">
  >>>.q-table td.no-padding{
    padding 0
  }
  >>>.q-field--with-bottom{
    padding-bottom 0
  }
  .q-table td{
    &>div{
      height 100%
    }
    .flex-1{
      flex 1
    }
    .item{
      width 100%
      padding 0 16px
      border-bottom $border
      &:last-child{
        border-color transparent
      }
    }
  }
</style>
